﻿using System;
using System.Collections.Generic;
using System.Text;
using EntLibEC.Info.Online;
using System.Data;
using EntLibEC.Dac;
using EntLibEC.Cmn;
using EntLibEC.Dac.Online;
using System.Collections;
using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace EntLibEC.Biz.Online
{
    public class OnlineListAreaManager
    {

        private static OnlineListAreaManager _instance;

        public static OnlineListAreaManager GetInstance()
        {
            if (_instance == null)
            {
                _instance = new OnlineListAreaManager();
            }
            return _instance;
        }

        /// <summary>
        ///  根据sysno装载OnlineListAreaInfo 实体类
        /// </summary>
        /// <param name="sysno"></param>
        /// <returns></returns>
        public OnlineListAreaInfo Load(int sysno)
        {
            string strSelect = "Select * from Ent_OnlineListArea with (nolock) where sysno=" + sysno.ToString();

            DataSet ds = SqlHelper.ExecuteDataSet(strSelect);
            if (!Util.HasMoreRow(ds))
                return null;

            OnlineListAreaInfo onlineListAreaInfo = new OnlineListAreaInfo();
            map(onlineListAreaInfo, ds.Tables[0].Rows[0]);

            return onlineListAreaInfo;
        }

        /// <summary>
        ///  新增前台显示区域
        /// </summary>
        /// <param name="oParam"></param>
        public void Insert(OnlineListAreaInfo oParam)
        {
            string sql = "select top 1 sysno from Ent_OnlineListArea with (nolock) where listAreaName='" + oParam.ListAreaName + "' or ListAreaKey=" + oParam.ListAreaKey.ToString();
            DataSet ds = SqlHelper.ExecuteDataSet(sql);
            if (Util.HasMoreRow(ds))
                throw new BizException("已经有相同的显示区域名称或者显示区域主键！");

            if (oParam.Category1SysNo != AppConst.IntNull && oParam.PagePosition != AppConst.IntNull)
            {
                sql = "Select top 1 sysno from Ent_OnlineListArea with (nolock) where Category1SysNo=" + oParam.Category1SysNo.ToString()
                    + " and PagePosition=" + oParam.PagePosition.ToString();

                ds = SqlHelper.ExecuteDataSet(sql);

                if (Util.HasMoreRow(ds))
                    throw new BizException("该产品目录和页面位置已经存在了！");
            }

            new OnlineListAreaDac().Insert(oParam);
        }

        public void Update(OnlineListAreaInfo oParam)
        {
            string sql = "select top 1 sysno from Ent_OnlineListArea with (nolock) where (listAreaName='" + oParam.ListAreaName + "' or ListAreaKey=" + oParam.ListAreaKey.ToString() + ") and SysNo != " + oParam.SysNo;
            DataSet ds = SqlHelper.ExecuteDataSet(sql);
            if (Util.HasMoreRow(ds))
                throw new BizException("已经有相同的显示区域名称或者显示区域主键！");

            if (oParam.Category1SysNo != AppConst.IntNull && oParam.PagePosition != AppConst.IntNull)
            {
                sql = "Select top 1 sysno from Ent_OnlineListArea with (nolock) where Category1SysNo=" + oParam.Category1SysNo.ToString()
                    + " and PagePosition=" + oParam.PagePosition.ToString()
                    + " and SysNo !=" + oParam.SysNo;

                ds = SqlHelper.ExecuteDataSet(sql);

                if (Util.HasMoreRow(ds))
                    throw new BizException("该产品目录和页面位置已经存在了！");
            }

            OnlineListAreaDac onlineListAreaDac = new OnlineListAreaDac();

            onlineListAreaDac.UpdateListArea(oParam);

            onlineListAreaDac.Update(oParam);
        }

        /// <summary>
        ///  查询
        /// </summary>
        /// <param name="paramHash"></param>
        /// <returns></returns>
        public DataSet GetOnlineListAreaDs(Hashtable paramHash)
        {
            string sql = @" select 
								onlineArea.*, (category1.C1ID+'-'+category1.C1Name) as CategoryName,UserName
							from 
								Ent_OnlineListArea onlineArea with (nolock)
                            left join Ent_Category1 category1 with (nolock) on onlineArea.Category1SysNo=category1.SysNo 
                            left join Ent_Sys_User internaluser with (nolock) on onlineArea.CreateUserSysNo=internaluser.SysNo
                            where 1=1 ";

            string sqlOrderBy = " order by onlineArea.ListOrder, onlineArea.SysNo";

            if (paramHash != null && paramHash.Count != 0)
            {
                StringBuilder sb = new StringBuilder(100);
                foreach (string key in paramHash.Keys)
                {
                    sb.Append(" and ");
                    object item = paramHash[key];

                    if (item is int)
                    {
                        sb.Append(key).Append("=").Append(item.ToString());
                    }
                    else if (item is string)
                    {
                        sb.Append(key).Append(" like ").Append(Util.ToSqlLikeString(item.ToString()));
                    }
                }
                sql += sb.ToString();           
            }

            sql += sqlOrderBy;

            return SqlHelper.ExecuteDataSet(sql);
        }

        private void map(OnlineListAreaInfo oParam, DataRow tempdr)
        {
            oParam.SysNo = Util.TrimIntNull(tempdr["SysNo"]);
            oParam.ListAreaName = Util.TrimNull(tempdr["ListAreaName"]);
            oParam.ListAreaKey = Util.TrimIntNull(tempdr["ListAreaKey"]);
            oParam.PagePosition = Util.TrimIntNull(tempdr["PagePosition"]);
            oParam.Category1SysNo = Util.TrimIntNull(tempdr["Category1SysNo"]);
            oParam.CreateUserSysNo = Util.TrimIntNull(tempdr["CreateUserSysNo"]);
            oParam.CreateTime = Util.TrimDateNull(tempdr["CreateTime"]);
            oParam.ListOrder = Util.TrimNull(tempdr["ListOrder"]);
        }

        /// <summary>
        ///  删除显示区域
        /// </summary>
        /// <param name="sysno"></param>
        /// <param name="listAreaKey"></param>
        public void Delete(int sysno, int listAreaKey)
        {
            OnlineListAreaDac onlineListAreaDac = new OnlineListAreaDac();

            if (onlineListAreaDac.ExistProductInArea(listAreaKey))
                throw new BizException("该显示区域已经有设置显示的产品，请首先删除产品列表。");
            else
                onlineListAreaDac.Delete(sysno);
        }

        public int? GetOnlineListAreaKey(string listAreaName)
        {
            Dictionary<string, int> dicListArea = new Dictionary<string, int>();

            // Attempt to retrieve from cache
            ICacheManager cache = CacheFactory.GetCacheManager();
            dicListArea = (Dictionary<string, int>)cache["ONLINELISTAREA"];

            // Retrieve from dataProvider if not in Cache
            if (dicListArea == null)
            {
                DataSet ds = GetOnlineListAreaDs(null);
                if (ds != null && ds.Tables.Count > 0)
                {
                    dicListArea = new Dictionary<string, int>();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        dicListArea.Add(row["ListAreaName"].ToString(), (int)row["ListAreaKey"]);
                    }
                    cache.Add("ONLINELISTAREA", dicListArea);
                }
            }

            // No data found.
            if (dicListArea == null || !dicListArea.ContainsKey(listAreaName))
                return null;

            return dicListArea[listAreaName];
        }

        public int? GetOnlineListAreaKey(int c1sysno, int pagePosition)
        {
            string strCategory = c1sysno.ToString() + "@" + pagePosition.ToString();
            Dictionary<string, int> dicListArea = new Dictionary<string, int>();

            // Attempt to retrieve from cache
            ICacheManager cache = CacheFactory.GetCacheManager();
            dicListArea = (Dictionary<string, int>)cache["ONLINELISTAREA_CATEGORY"];

            // Retrieve from dataProvider if not in Cache
            if (dicListArea == null)
            {
                DataSet ds = GetOnlineListAreaCategoryDs();
                if (ds != null && ds.Tables.Count > 0)
                {
                    dicListArea = new Dictionary<string, int>();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        dicListArea.Add(row["Category1SysNo"].ToString()+"@"+row["PagePosition"].ToString(), (int)row["ListAreaKey"]);
                    }
                    cache.Add("ONLINELISTAREA_CATEGORY", dicListArea);
                }
            }

            // No data found.
            if (dicListArea == null || !dicListArea.ContainsKey(strCategory))
                return null;

            return dicListArea[strCategory];
        }

        public DataSet GetOnlineListAreaCategoryDs()
        {
            string strSelect = "Select * from Ent_OnlineListArea with (nolock) where Category1SysNo is not null and PagePosition is not null";

            return SqlHelper.ExecuteDataSet(strSelect);
        }
    }
}
